package TestDemo6;

// 创建一个单例的类
// 饿汉方式实现.
// 饿 的意思是 "迫切"
// 在类被加载的时候, 就会创建出这个单例的实例
class Singleton {
    private static Singleton instance = new Singleton();

    public static Singleton getInstance() {
        return instance;
    }

    // 单例模式的最关键部分.
    private Singleton() { }
}

public class Demo24 {
    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        System.out.println(s1 == s2);

    }
}



//class  SingletonLazy {
//
////    声明一个成员变量
//    private static  SingletonLazy singletonLazy;
//
//    public static SingletonLazy getSingletonLazy() {
////        如果该对象没有被实例,还需要使用的话,就需要先是实例化
//        if (singletonLazy == null) {
//            singletonLazy = new SingletonLazy();
//        }
//
//        return singletonLazy;
//    }
//
//    // 关键一步，把构造方法私有化
//    private SingletonLazy() {
//
//    }
//}


//class Demo25 {
//    public static void main(String[] args) {
////        接收两次
//        SingletonLazy singletonLazy1 = SingletonLazy.getSingletonLazy();
//        SingletonLazy singletonLazy2 = SingletonLazy.getSingletonLazy();
//
////        判断两次是否是相同的对象
//        System.out.println(singletonLazy1 == singletonLazy2);
//    }
//}







// 懒汉模式实现的单例模式
class SingletonLazy {
    // 此处先把这个实例的引用设为 null, 先不着急创建实例.
    private static volatile  SingletonLazy instance = null;
    private static Object locker = new Object();

    public static SingletonLazy getInstance() {
        // 在这个条件中判定当前是否应该要加锁.
        if (instance == null) {
            synchronized (locker) {
                if (instance == null) {
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }

    private SingletonLazy() { }
}

class Demo25 {
   private static SingletonLazy s1;

   private static SingletonLazy s2;

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(()->{
            s1 = SingletonLazy.getInstance();
        });
        Thread t2 = new Thread(()->{
            s2 = SingletonLazy.getInstance();
        });

        t1.start();
        t2.start();

        Thread.sleep(1000);

        System.out.println(s1 == s2);
    }
}